package com.yu8home.opcua.test;

import com.yu8home.opcua.OpcUAUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.milo.opcua.sdk.client.subscriptions.EventFilterBuilder;
import org.eclipse.milo.opcua.sdk.client.subscriptions.ManagedEventItem;
import org.eclipse.milo.opcua.sdk.client.subscriptions.ManagedSubscription;
import org.eclipse.milo.opcua.stack.core.Identifiers;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName;
import org.eclipse.milo.opcua.stack.core.types.builtin.Variant;
import org.eclipse.milo.opcua.stack.core.types.structured.EventFilter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@Slf4j
public class D {

    public static void main(String[] args) throws Exception {
        OpcUAUtil.getConnect();
        eee();

        System.in.read();
    }


    private static void eee4() throws Exception {
        ManagedSubscription subscription = ManagedSubscription.create(OpcUAUtil.opcUaClient);

//        List<NodeId> nodeIds = new ArrayList<>();
//        for (String s : subscribes) {
//            nodeIds.add(new NodeId(Conn.namespaceIndex, s));
//        }
//
//
//
//        List<EventFilter> eventFilters = new ArrayList<>();
//
//        List<ManagedEventItem> eventItems = subscription.createEventItems(nodeIds, eventFilters);
//        for (ManagedEventItem t : eventItems) {
//            t.addEventValueListener(f -> {
//                log.info("=====identifier：{}", t.getNodeId().getIdentifier());
//                for (Variant variant : f) {
//                    log.info("=====value：{}", variant.getValue());
//                }
//            });
//        }


        CountDownLatch eventLatch = new CountDownLatch(3);

        subscription.addEventChangeListener((eventItems, variants) -> {
            for (int i = 0; i < eventItems.size(); ++i) {
                ManagedEventItem eventItem = (ManagedEventItem) eventItems.get(i);
                Variant[] eventFieldValues = (Variant[]) variants.get(i);
                log.info("Event Received from {}", eventItem.getNodeId());

                for (int j = 0; j < eventFieldValues.length; ++j) {
                    log.info("\tvariant[{}]: {}", j, eventFieldValues[j].getValue());
                }
            }
            eventLatch.countDown();
        });
//        EventFilter eventFilter = (new EventFilterBuilder()).select(Identifiers.BaseEventType, new QualifiedName(0, "EventId")).select(Identifiers.BaseEventType, new QualifiedName(0, "EventType")).select(Identifiers.BaseEventType, new QualifiedName(0, "Severity")).select(Identifiers.BaseEventType, new QualifiedName(0, "Time")).select(Identifiers.BaseEventType, new QualifiedName(0, "Message")).build();
//        ManagedEventItem eventItem = subscription.createEventItem(Identifiers.Server, eventFilter);
//        eventItem.delete();


        eventLatch.await();
    }


    private static void eee() throws Exception {
        ManagedSubscription subscription = ManagedSubscription.create(OpcUAUtil.opcUaClient);

        List<NodeId> nodeIds = new ArrayList<>();
        List<EventFilter> eventFilters = new ArrayList<>();

        for (String s : Const.subscribes) {
            NodeId nodeId = new NodeId(OpcUAUtil.namespaceIndex, s);
            nodeIds.add(nodeId);

            EventFilter eventFilter = (new EventFilterBuilder())
                    // .select(Identifiers.BaseEventType, new QualifiedName(Conn.namespaceIndex, "EventId"))
                    // .select(Identifiers.BaseEventType, new QualifiedName(Conn.namespaceIndex, "EventType"))
                    .select(Identifiers.BaseEventType, new QualifiedName(OpcUAUtil.namespaceIndex, "Severity"))
                    .select(Identifiers.BaseEventType, new QualifiedName(OpcUAUtil.namespaceIndex, "Time"))
                    .select(Identifiers.BaseEventType, new QualifiedName(OpcUAUtil.namespaceIndex, "Message"))
                    .build();

            eventFilters.add(eventFilter);


            log.info("=========aaaaa==========");


            //  ManagedEventItem eventItem =

            subscription.createEventItem(nodeId, eventFilter);
            log.info("=========bbbbb==========");
        }

        Thread.sleep(10 * 1000);

        List<ManagedEventItem> items = subscription.getEventItems();

        log.info("=========items.size=========={}", items.size());
        for (ManagedEventItem e : items) {
            e.addEventValueListener(f -> {
                log.info("=====identifier：{}", e.getNodeId().getIdentifier());
                for (Variant variant : f) {
                    log.info("=====value：{}", variant.getValue());
                }
            });


            log.info("=========kkkkkk==========");
        }


        CountDownLatch eventLatch = new CountDownLatch(3);

        subscription.addEventChangeListener((eventItems, variants) -> {
            for (int i = 0; i < eventItems.size(); ++i) {
                ManagedEventItem eventItem = (ManagedEventItem) eventItems.get(i);
                Variant[] eventFieldValues = (Variant[]) variants.get(i);
                log.info("Event Received from {}", eventItem.getNodeId());

                for (int j = 0; j < eventFieldValues.length; ++j) {
                    log.info("\tvariant[{}]: {}", j, eventFieldValues[j].getValue());
                }
            }

            log.info("===========1============={}", eventLatch.getCount());
            eventLatch.countDown();
            log.info("===========2============={}", eventLatch.getCount());
        });
        log.info("===========3============={}", eventLatch.getCount());
        // eventLatch.await();
        log.info("===========4============={}", eventLatch.getCount());


        //  System.in.read();
    }


//    public static void main(String[] args) throws Exception {
//        long a = System.currentTimeMillis();
//        connect();
//        log.info("connect耗时：{}", System.currentTimeMillis() - a);
//
//        //CountDownLatch eventLatch = new CountDownLatch(3);
//        ManagedSubscription subscription = ManagedSubscription.create(opcUaClient);
//        subscription.addEventChangeListener((eventItems, variants) -> {
//            for (int i = 0; i < eventItems.size(); ++i) {
//                ManagedEventItem eventItem = (ManagedEventItem) eventItems.get(i);
//                Variant[] eventFieldValues = (Variant[]) variants.get(i);
//                log.info("Event Received from {}", eventItem.getNodeId());
//
//                for (int j = 0; j < eventFieldValues.length; ++j) {
//                    log.info("\tvariant[{}]: {}", j, eventFieldValues[j].getValue());
//                }
//            }
//
//            // eventLatch.countDown();
//        });
//
//        // eventLatch.await();
//        // eventItem.delete();
////        future.complete(client);
//
//
//        log.info("==============9999============");
//        System.in.read();
//    }


}
